"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : autocommit
Case Name   : 关闭自动提交，测试设置当前事务特性(读已提交, 只读)，执行写操作时合理报错
Create At   : 2023/01/17
@zou_jialiang0501162244
Description :
    1、开启session1在兼容B库建表插入数据，session2查询后清空表数据
    2、开启session2关闭自动提交，设置隔离级别读已提交，访问模式只读，查询表，
    session1清空表数据后再查询，表中插入数据
    3、清理环境
Expect      :
    1、执行成功
    2、设置成功，前后查询1条数据和无数据，insert报错
    3、成功
History     :
"""

import os
import time
import unittest

from testcase.utils.Logger import Logger
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.ComThread import ComThread


class TestAutocommit(unittest.TestCase):

    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.constant = Constant()
        self.tb_name = 't_autocommit_0019'
        self.db_name = 'db_autocommit_0019'
        self.log.info("-----预置兼容B库-----")
        preset_db = f"drop database if exists {self.db_name};" \
                    f"create database {self.db_name} dbcompatibility 'B';"
        preset_db_res = self.pri_sh.execut_db_sql(preset_db)
        self.log.info(preset_db_res)
        self.assertIn(self.constant.CREATE_DATABASE_SUCCESS, preset_db_res,
                      f"创建兼容B库失败")

    def test_autocommit(self):
        text1 = '-----step1:开启session1在兼容B库建表插入数据，' \
                'session2查询后清空表数据;expect执行成功-----'
        self.log.info(text1)
        sql1 = f"drop table if exists {self.tb_name} cascade;" \
               f"create table {self.tb_name}(c_int int primary key, " \
               f"c_varchar varchar(20) not null);" \
               f"insert into {self.tb_name} values(11, 'committed');" \
               f"select pg_sleep(5);" \
               f"delete from {self.tb_name};"
        session1 = ComThread(self.pri_sh.execut_db_sql,
                             args=(sql1, '', self.db_name))
        session1.setDaemon(True)

        text2 = '-----step2:session2关闭自动提交，设置隔离级别读已提交，访' \
                '问模式只读，查询表，session1清空表数据后再查询，表中插入数' \
                '据;expect:设置成功，前后查询1条数据和无数据，insert报错-----'
        self.log.info(text2)
        sql2 = f"set autocommit=0;" \
               f"set local transaction isolation level " \
               f"read committed read only;" \
               f"show transaction_isolation;" \
               f"select * from {self.tb_name};" \
               f"select pg_sleep(5);" \
               f"select * from {self.tb_name};" \
               f"insert into {self.tb_name} values(1, 1);"
        session2 = ComThread(self.pri_sh.execut_db_sql,
                             args=(sql2, '', self.db_name))
        session2.setDaemon(True)
        # 先后启动线程，间隔1s
        session1.start()
        time.sleep(2)
        session2.start()
        session1.join(10)
        session2.join(10)
        result1 = session1.get_result()
        self.log.info(f'session1_results: {result1}')
        result2 = session2.get_result()
        self.log.info(f'session2_results: {result2}')
        self.assertEqual(result1.count(self.constant.CREATE_TABLE_SUCCESS), 2,
                         f"建表失败: {text1}")
        self.assertIn(self.constant.INSERT_SUCCESS_MSG, result1,
                      f"表中插入数据失败: {text1}")
        self.assertIn(self.constant.DELETE_SUCCESS_MSG, result1,
                      f"删除表数据失败: {text1}")
        self.assertEqual(result2.count('SET'), 2, f"执行失败: {text2}")
        self.assertIn(self.constant.READ_COMMITED_MSG, result2,
                      f"执行失败: {text2}")
        self.assertIn('11 | committed', result2, f"执行失败{text2}")
        self.assertEqual(result2.splitlines()[-3].strip(), '(0 rows)',
                         f"执行失败{text2}")
        self.assertIn(self.constant.READ_ONLY_ERROR_MSG, result2,
                      f"执行失败: {text2}")

    def tearDown(self):
        text3 = '-----step3:清理环境 expect:成功-----'
        self.log.info(text3)
        drop_db_res = self.pri_sh.execut_db_sql(
            f"drop database if exists {self.db_name};")
        self.log.info(drop_db_res)
        self.assertIn(self.constant.DROP_DATABASE_SUCCESS, drop_db_res,
                      f"执行失败: {text3}")
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
